/**
 * Created by luqidong on 2017/5/31.
 */
(function () {
    /**
     *　　　　　　　　┏┓　　　┏┓+ +
     *　　　　　　　┏┛┻━━━┛┻┓ + +
     *　　　　　　　┃　　　　　　　┃ 　
     *　　　　　　　┃　　　━　　　┃ ++ + + +
     *　　　　　　 ████━████ ┃+
     *　　　　　　　┃　　　　　　　┃ +
     *　　　　　　　┃　　  ┻　　　┃
     *　　　　　　　┃　　　　　　　┃ + +
     *　　　　　　　┗━┓　　　┏━┛
     *　　　　　　　　　┃　　　┃　　　　　　　　　　　
     *　　　　　　　　　┃　　　┃ + + + +
     *　　　　　　　　　┃　　　┃　　　　Code is far away from bug with the animal protecting　　　　　　　
     *　　　　　　　　　┃　　　┃ + 　　　　神兽保佑,代码无bug　　
     *　　　　　　　　　┃　　　┃
     *　　　　　　　　　┃　　　┃　　+　　　　　　　　　
     *　　　　　　　　　┃　 　　┗━━━┓ + +
     *　　　　　　　　　┃ 　　　　　　　┣┓
     *　　　　　　　　　┃ 　　　　　　　┏┛
     *　　　　　　　　　┗┓┓┏━┳┓┏┛ + + + +
     *　　　　　　　　　　┃┫┫　┃┫┫
     *　　　　　　　　　　┗┻┛　┗┻┛+ + + +
     */

// 获取webView 游览器类型，android或ios
    var mobileType, ua = navigator.userAgent;
    console.log('ua', ua);
    // = .indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1
    if(ua.indexOf('tdlovedouapp') < 0) {
        window.TDbridge = {};
        return;
    }
    mobileType = ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1;
    if(mobileType) {
        // android 初始化方法体
        if(typeof QWJSBridge === "undefined") {
            if(typeof(DeviceInfo) !== 'object') {
                var DeviceInfo = {};
            }
            var QWJSBridge = {
                queue: {
                    ready: true,
                    commands: [],
                    timer: null
                },
                documentEventHandler: {}, // Collection of custom document event handlers
                windowEventHandler: {} // Collection of custom window event handlers
            };

            QWJSBridge.resources = {
                base: true
            };
            QWJSBridge.hasResource = function (name) {
                return QWJSBridge.resources[name];
            };

            /**
             * Add a resource to list of loaded resources by QWJSBridge
             *
             * @param name
             */
            QWJSBridge.addResource = function (name) {
                QWJSBridge.resources[name] = true;
            };

            /**
             * Custom pub-sub channel that can have functions subscribed to it
             * @constructor
             */
            QWJSBridge.Channel = function (type) {
                this.type = type;
                this.handlers = {};
                this.guid = 0;
                this.fired = false;
                this.enabled = true;
            };

            QWJSBridge.Channel.prototype.subscribe = function (f, c, g) {
                // need a function to call
                if(f === null) {
                    return;
                }

                var func = f;
                if(typeof c === "object" && typeof f === "function") {
                    func = QWJSBridge.close(c, f);
                }

                g = g || func.observer_guid || f.observer_guid || this.guid++;
                func.observer_guid = g;
                f.observer_guid = g;
                this.handlers[g] = func;
                return g;
            };

            /**
             * Like subscribe but the function is only called once and then it
             * auto-unsubscribes itself.
             */
            QWJSBridge.Channel.prototype.subscribeOnce = function (f, c) {
                var g = null;
                var _this = this;
                var m = function () {
                    f.apply(c || null, arguments);
                    _this.unsubscribe(g);
                };
                if(this.fired) {
                    if(typeof c === "object" && typeof f === "function") {
                        f = QWJSBridge.close(c, f);
                    }
                    f.apply(this, this.fireArgs);
                } else {
                    g = this.subscribe(m);
                }
                return g;
            };

            /**
             * Unsubscribes the function with the given guid from the channel.
             */
            QWJSBridge.Channel.prototype.unsubscribe = function (g) {
                if(typeof g === "function") {
                    g = g.observer_guid;
                }
                this.handlers[g] = null;
                delete this.handlers[g];
            };

            /**
             * Calls all functions subscribed to this channel.
             */
            QWJSBridge.Channel.prototype.fire = function (e) {
                if(this.enabled) {
                    var fail = false;
                    var item, handler, rv;
                    for (item in this.handlers) {
                        if(this.handlers.hasOwnProperty(item)) {
                            handler = this.handlers[item];
                            if(typeof handler === "function") {
                                rv = (handler.apply(this, arguments) === false);
                                fail = fail || rv;
                            }
                        }
                    }
                    this.fired = true;
                    this.fireArgs = arguments;
                    return !fail;
                }
                return true;
            };

            /**
             * Calls the provided function only after all of the channels specified
             * have been fired.
             */
            QWJSBridge.Channel.join = function (h, c) {
                var i = c.length;
                var f = function () {
                    if(!(--i)) {
                        h();
                    }
                };
                var len = i;
                var j;
                for (j = 0; j < len; j++) {
                    if(!c[j].fired) {
                        c[j].subscribeOnce(f);
                    } else {
                        i--;
                    }
                }
                if(!i) {
                    h();
                }
            };

            /**
             * Boolean flag indicating if the QWJSBridge API is available and initialized.
             */ // TODO: Remove this, it is unused here ... -jm
            QWJSBridge.available = DeviceInfo.uuid !== undefined;

            /**
             * Add an initialization function to a queue that ensures it will run and initialize
             * application constructors only once QWJSBridge has been initialized.
             * @param {Function} func The function callback you want run once QWJSBridge is initialized
             */
            QWJSBridge.addConstructor = function (func) {
                QWJSBridge.onQWJSBridgeInit.subscribeOnce(function () {
                    try {
                        func();
                    } catch (e) {
                        console.log("Failed to run constructor: " + e);
                    }
                });
            };

            /**
             * Plugins object
             */
            if(!window.plugins) {
                window.plugins = {};
            }

            /**
             * Adds a plugin object to window.plugins.
             * The plugin is accessed using window.plugins.<name>
             *
             * @param name          The plugin name
             * @param obj           The plugin object
             */
            QWJSBridge.addPlugin = function (name, obj) {
                if(!window.plugins[name]) {
                    window.plugins[name] = obj;
                } else {
                    console.log("Error: Plugin " + name + " already exists.");
                }
            };

            /**
             * onDOMContentLoaded channel is fired when the DOM content
             * of the page has been parsed.
             */
            QWJSBridge.onDOMContentLoaded = new QWJSBridge.Channel('onDOMContentLoaded');

            /**
             * onNativeReady channel is fired when the QWJSBridge native code
             * has been initialized.
             */
            QWJSBridge.onNativeReady = new QWJSBridge.Channel('onNativeReady');

            /**
             * onQWJSBridgeInit channel is fired when the web page is fully loaded and
             * QWJSBridge native code has been initialized.
             */
            QWJSBridge.onQWJSBridgeInit = new QWJSBridge.Channel('onQWJSBridgeInit');

            /**
             * onQWJSBridgeReady channel is fired when the JS QWJSBridge objects have been created.
             */
            QWJSBridge.onQWJSBridgeReady = new QWJSBridge.Channel('onQWJSBridgeReady');

            /**
             * onQWJSBridgeInfoReady channel is fired when the QWJSBridge device properties
             * has been set.
             */
            QWJSBridge.onQWJSBridgeInfoReady = new QWJSBridge.Channel('onQWJSBridgeInfoReady');

            /**
             * onQWJSBridgeConnectionReady channel is fired when the QWJSBridge connection properties
             * has been set.
             */
            QWJSBridge.onQWJSBridgeConnectionReady = new QWJSBridge.Channel('onQWJSBridgeConnectionReady');

            /**
             * onDestroy channel is fired when the QWJSBridge native code
             * is destroyed.  It is used internally.
             * Window.onunload should be used by the user.
             */
            QWJSBridge.onDestroy = new QWJSBridge.Channel('onDestroy');
            QWJSBridge.onDestroy.subscribeOnce(function () {
                QWJSBridge.shuttingDown = true;
            });
            QWJSBridge.shuttingDown = false;

            // _nativeReady is global variable that the native side can set
            // to signify that the native code is ready. It is a global since
            // it may be called before any QWJSBridge JS is ready.
            if(typeof _nativeReady !== 'undefined') {
                QWJSBridge.onNativeReady.fire();
            }

            /**
             * onDeviceReady is fired only after all QWJSBridge objects are created and
             * the device properties are set.
             */
            QWJSBridge.onDeviceReady = new QWJSBridge.Channel('onDeviceReady');


            // Array of channels that must fire before "deviceready" is fired
            QWJSBridge.deviceReadyChannelsArray = [QWJSBridge.onQWJSBridgeReady, QWJSBridge.onQWJSBridgeInfoReady, QWJSBridge.onQWJSBridgeConnectionReady];

            // Hashtable of user defined channels that must also fire before "deviceready" is fired
            QWJSBridge.deviceReadyChannelsMap = {};

            /**
             * Indicate that a feature needs to be initialized before it is ready to be used.
             * This holds up QWJSBridge's "deviceready" event until the feature has been initialized
             * and QWJSBridge.initComplete(feature) is called.
             *
             * @param feature {String}     The unique feature name
             */
            QWJSBridge.waitForInitialization = function (feature) {
                if(feature) {
                    var channel = new QWJSBridge.Channel(feature);
                    QWJSBridge.deviceReadyChannelsMap[feature] = channel;
                    QWJSBridge.deviceReadyChannelsArray.push(channel);
                }
            };

            /**
             * Indicate that initialization code has completed and the feature is ready to be used.
             *
             * @param feature {String}     The unique feature name
             */
            QWJSBridge.initializationComplete = function (feature) {
                var channel = QWJSBridge.deviceReadyChannelsMap[feature];
                if(channel) {
                    channel.fire();
                }
            };

            /**
             * Create all QWJSBridge objects once page has fully loaded and native side is ready.
             */
            QWJSBridge.Channel.join(function () {

                // Start listening for XHR callbacks
                setTimeout(function () {
                    if(QWJSBridge.UsePolling) {
                        QWJSBridge.JSCallbackPolling();
                    } else {
                        var polling = prompt("usePolling", "gap_callbackServer:");

                        QWJSBridge.UsePolling = polling;
                        if(polling == "true") {
                            QWJSBridge.UsePolling = true;
                            QWJSBridge.JSCallbackPolling();
                        } else {
                            QWJSBridge.UsePolling = false;
                            QWJSBridge.JSCallback();
                        }
                    }
                }, 1);

                // Run QWJSBridge constructors
                QWJSBridge.onQWJSBridgeInit.fire();

                // Fire event to notify that all objects are created
                QWJSBridge.onQWJSBridgeReady.fire();

                // Fire onDeviceReady event once all constructors have run and QWJSBridge info has been
                // received from native side, and any user defined initialization channels.
                QWJSBridge.Channel.join(function () {
                    // Let native code know we are inited on JS side
                    prompt("", "gap_init:");

                    QWJSBridge.onDeviceReady.fire();
                }, QWJSBridge.deviceReadyChannelsArray);

            }, [QWJSBridge.onDOMContentLoaded, QWJSBridge.onNativeReady]);

            // Listen for DOMContentLoaded and notify our channel subscribers
            document.addEventListener('DOMContentLoaded', function () {
                QWJSBridge.onDOMContentLoaded.fire();
            }, false);

            // Intercept calls to document.addEventListener and watch for deviceready
            QWJSBridge.m_document_addEventListener = document.addEventListener;

            // Intercept calls to window.addEventListener
            QWJSBridge.m_window_addEventListener = window.addEventListener;

            /**
             * Add a custom window event handler.
             *
             * @param {String} event            The event name that callback handles
             * @param {Function} callback       The event handler
             */
            QWJSBridge.addWindowEventHandler = function (event, callback) {
                QWJSBridge.windowEventHandler[event] = callback;
            };

            /**
             * Add a custom document event handler.
             *
             * @param {String} event            The event name that callback handles
             * @param {Function} callback       The event handler
             */
            QWJSBridge.addDocumentEventHandler = function (event, callback) {
                QWJSBridge.documentEventHandler[event] = callback;
            };


            QWJSBridge.callbackId = 0;
            QWJSBridge.callbacks = {};
            QWJSBridge.callbackStatus = {
                NO_RESULT: 0,
                OK: 1,
                CLASS_NOT_FOUND_EXCEPTION: 2,
                ILLEGAL_ACCESS_EXCEPTION: 3,
                INSTANTIATION_EXCEPTION: 4,
                MALFORMED_URL_EXCEPTION: 5,
                IO_EXCEPTION: 6,
                INVALID_ACTION: 7,
                JSON_EXCEPTION: 8,
                ERROR: 9
            };


            /**
             * Execute a QWJSBridge command.  It is up to the native side whether this action is synch or async.
             * The native side can return:
             *      Synchronous: PluginResult object as a JSON string
             *      Asynchrounous: Empty string ""
             * If async, the native side will QWJSBridge.callbackSuccess or QWJSBridge.callbackError,
             * depending upon the result of the action.
             *
             * @param {Function} success    The success callback
             * @param {Function} fail       The fail callback
             * @param {String} service      The name of the service to use
             * @param {String} action       Action to be run in QWJSBridge
             * @param {Array.<String>} [args]     Zero or more arguments to pass to the method
             */
            QWJSBridge.exec = function (success, service, action, args) {
                try {
                    var callbackId = service + QWJSBridge.callbackId++;
                    var fail = null;
                    if(success || fail) {
                        QWJSBridge.callbacks[callbackId] = {
                            success: success,
                            fail: fail
                        };
                    }

                    console.log(args)
                    console.log(JSON.stringify(args), "gap:" + JSON.stringify([service, action, callbackId, true]));
                    var r = prompt(JSON.stringify(args), "gap:" + JSON.stringify([service, action, callbackId, true]));
                    // If a result was returned
                    if(r.length > 0) {
                        eval("var v=" + r + ";")
                        // If status is OK, then return value back to caller
                        if(v.status === QWJSBridge.callbackStatus.OK) {
                            alert('ok')
                            // If there is a success callback, then call it now with
                            // returned value
                            if(success) {
                                try {
                                    console.log('执行');
                                    success(v.message);
                                } catch (e) {
                                    console.log("Error in success callback: " + callbackId + " = " + e);
                                }

                                // Clear callback if not expecting any more results
                                if(!v.keepCallback) {
                                    delete QWJSBridge.callbacks[callbackId];
                                }
                            }
                            return v.message;
                        }

                        // If no result
                        else if(v.status === QWJSBridge.callbackStatus.NO_RESULT) {

                            // Clear callback if not expecting any more results
                            if(!v.keepCallback) {
                                delete QWJSBridge.callbacks[callbackId];
                            }
                        }

                        // If error, then display error
                        else {
                            console.log("Error: Status=" + v.status + " Message=" + v.message);

                            // If there is a fail callback, then call it now with returned value
                            if(fail) {
                                try {
                                    fail(v.message);
                                } catch (e1) {
                                    console.log("Error in error callback: " + callbackId + " = " + e1);
                                }

                                // Clear callback if not expecting any more results
                                if(!v.keepCallback) {
                                    delete QWJSBridge.callbacks[callbackId];
                                }
                            }
                            return null;
                        }
                    }
                } catch (e2) {
                    console.log("Error: " + e2);
                }
            };

            /**
             * Called by native code when returning successful result from an action.
             *
             * @param callbackId
             * @param args
             */
            QWJSBridge.callbackSuccess = function (callbackId, args) {
                if(QWJSBridge.callbacks[callbackId]) {

                    // If result is to be sent to callback
                    //if (args.status === QWJSBridge.callbackStatus.OK) {
                    try {
                        if(QWJSBridge.callbacks[callbackId].success) {
                            QWJSBridge.callbacks[callbackId].success(args.message);
                        }
                    } catch (e) {
                        console.log("Error in success callback: " + callbackId + " = " + e);
                    }
                    //}

                    // Clear callback if not expecting any more results
                    if(!args.keepCallback) {
                        delete QWJSBridge.callbacks[callbackId];
                    }
                }
            };

            /**
             * Called by native code when returning error result from an action.
             *
             * @param callbackId
             * @param args
             */
            QWJSBridge.callbackError = function (callbackId, args) {
                if(QWJSBridge.callbacks[callbackId]) {
                    try {
                        if(QWJSBridge.callbacks[callbackId].fail) {
                            QWJSBridge.callbacks[callbackId].fail(args.message);
                        }
                    } catch (e) {
                        console.log("Error in error callback: " + callbackId + " = " + e);
                    }

                    // Clear callback if not expecting any more results
                    if(!args.keepCallback) {
                        delete QWJSBridge.callbacks[callbackId];
                    }
                }
            };


            /**
             * Internal function used to dispatch the request to QWJSBridge.  It processes the
             * command queue and executes the next command on the list.  If one of the
             * arguments is a JavaScript object, it will be passed on the QueryString of the
             * url, which will be turned into a dictionary on the other end.
             * @private
             */
            // TODO: Is this used?
            QWJSBridge.run_command = function () {
                if(!QWJSBridge.available || !QWJSBridge.queue.ready) {
                    return;
                }
                QWJSBridge.queue.ready = false;

                var args = QWJSBridge.queue.commands.shift();
                if(QWJSBridge.queue.commands.length === 0) {
                    clearInterval(QWJSBridge.queue.timer);
                    QWJSBridge.queue.timer = null;
                }

                var uri = [];
                var dict = null;
                var i;
                for (i = 1; i < args.length; i++) {
                    var arg = args[i];
                    if(arg === undefined || arg === null) {
                        arg = '';
                    }
                    if(typeof(arg) === 'object') {
                        dict = arg;
                    } else {
                        uri.push(encodeURIComponent(arg));
                    }
                }
                var url = "gap://" + args[0] + "/" + uri.join("/");
                if(dict !== null) {
                    var name;
                    var query_args = [];
                    for (name in dict) {
                        if(dict.hasOwnProperty(name) && (typeof(name) === 'string')) {
                            query_args.push(encodeURIComponent(name) + "=" + encodeURIComponent(dict[name]));
                        }
                    }
                    if(query_args.length > 0) {
                        url += "?" + query_args.join("&");
                    }
                }
                document.location = url;

            };

            QWJSBridge.JSCallbackPort = null;
            QWJSBridge.JSCallbackToken = null;

            /**
             * This is only for Android.
             *
             * Internal function that uses XHR to call into QWJSBridge Java code and retrieve
             * any JavaScript code that needs to be run.  This is used for callbacks from
             * Java to JavaScript.
             */
            QWJSBridge.JSCallback = function () {

                // Exit if shutting down app
                if(QWJSBridge.shuttingDown) {
                    return;
                }

                // If polling flag was changed, start using polling from now on
                if(QWJSBridge.UsePolling) {
                    QWJSBridge.JSCallbackPolling();
                    return;
                }

                var xmlhttp = new XMLHttpRequest();

                // Callback function when XMLHttpRequest is ready
                xmlhttp.onreadystatechange = function () {
                    if(xmlhttp.readyState === 4) {

                        // Exit if shutting down app
                        if(QWJSBridge.shuttingDown) {
                            return;
                        }

                        // If callback has JavaScript statement to execute
                        if(xmlhttp.status === 200) {

                            // Need to url decode the response
                            var msg = decodeURIComponent(xmlhttp.responseText);
                            setTimeout(function () {
                                try {
                                    var t = eval(msg);
                                } catch (e) {
                                    // If we're getting an error here, seeing the message will help in debugging
                                    console.log("JSCallback: Message from Server: " + msg);
                                    console.log("JSCallback Error: " + e);
                                }
                            }, 1);
                            setTimeout(QWJSBridge.JSCallback, 1);
                        }

                        // If callback ping (used to keep XHR request from timing out)
                        else if(xmlhttp.status === 404) {
                            setTimeout(QWJSBridge.JSCallback, 10);
                        }

                        // If security error
                        else if(xmlhttp.status === 403) {
                            console.log("JSCallback Error: Invalid token.  Stopping callbacks.");
                        }

                        // If server is stopping
                        else if(xmlhttp.status === 503) {
                            console.log("JSCallback Server Closed: Stopping callbacks.");
                        }

                        // If request wasn't GET
                        else if(xmlhttp.status === 400) {
                            console.log("JSCallback Error: Bad request.  Stopping callbacks.");
                        }

                        // If error, revert to polling
                        else {
                            console.log("JSCallback Error: Request failed.");
                            QWJSBridge.UsePolling = true;
                            QWJSBridge.JSCallbackPolling();
                        }
                    }
                };

                if(QWJSBridge.JSCallbackPort === null) {
                    QWJSBridge.JSCallbackPort = prompt("getPort", "gap_callbackServer:");
                }
                if(QWJSBridge.JSCallbackToken === null) {
                    QWJSBridge.JSCallbackToken = prompt("getToken", "gap_callbackServer:");
                }
                xmlhttp.open("GET", "http://127.0.0.1:" + QWJSBridge.JSCallbackPort + "/" + QWJSBridge.JSCallbackToken, true);
                xmlhttp.send();
            };

            /**
             * The polling period to use with JSCallbackPolling.
             * This can be changed by the application.  The default is 50ms.
             */
            QWJSBridge.JSCallbackPollingPeriod = 50;

            /**
             * Flag that can be set by the user to force polling to be used or force XHR to be used.
             */
            QWJSBridge.UsePolling = false; // T=use polling, F=use XHR

            /**
             * This is only for Android.
             *
             * Internal function that uses polling to call into QWJSBridge Java code and retrieve
             * any JavaScript code that needs to be run.  This is used for callbacks from
             * Java to JavaScript.
             */
            QWJSBridge.JSCallbackPolling = function () {

                // Exit if shutting down app
                if(QWJSBridge.shuttingDown) {
                    return;
                }

                // If polling flag was changed, stop using polling from now on
                if(!QWJSBridge.UsePolling) {
                    QWJSBridge.JSCallback();
                    return;
                }

                var msg = prompt("", "gap_poll:");
                if(msg) {
                    setTimeout(function () {
                        try {
                            var t = eval("" + msg);
                        } catch (e) {
                            console.log("JSCallbackPolling: Message from Server: " + msg);
                            console.log("JSCallbackPolling Error: " + e);
                        }
                    }, 1);
                    setTimeout(QWJSBridge.JSCallbackPolling, 1);
                } else {
                    setTimeout(QWJSBridge.JSCallbackPolling, QWJSBridge.JSCallbackPollingPeriod);
                }
            };
        }
    } else {
        QWJSBridge = {
            queue: {
                ready: true,
                commands: [],
                timer: null
            },
            _constructors: []
        };
        QWJSBridge.sessionKey = 0;
        QWJSBridge.resources = {
            base: true
        };
        QWJSBridge.hasResource = function (name) {
            return QWJSBridge.resources[name];
        };
        QWJSBridge.addResource = function (name) {
            QWJSBridge.resources[name] = true;
        };
        (function () {
            var timer = setInterval(function () {
                var state = document.readyState;
                if((state == 'loaded' || state == 'complete')) {
                    clearInterval(timer);
                    while (setInterval._constructors && setInterval._constructors.length > 0) {
                        var constructor = setInterval._constructors.shift();
                        try {
                            constructor();
                        } catch (e) {
                            if(typeof(console['log']) == 'function') {
                                console.log("Failed to run constructor: " + console.processMessage(e));
                            } else {

                            }
                        }
                    }
                    var e = document.createEvent('Events');
                    e.initEvent('deviceready');
                    document.dispatchEvent(e);
                }
            }, 1);
        })();
        QWJSBridge.callbackId = 0;
        QWJSBridge.callbacks = {};
        QWJSBridge.callbackStatus = {
            NO_RESULT: 0,
            OK: 1,
            CLASS_NOT_FOUND_EXCEPTION: 2,
            ILLEGAL_ACCESS_EXCEPTION: 3,
            INSTANTIATION_EXCEPTION: 4,
            MALFORMED_URL_EXCEPTION: 5,
            IO_EXCEPTION: 6,
            INVALID_ACTION: 7,
            JSON_EXCEPTION: 8,
            ERROR: 9
        };
        QWJSBridge.exec = function () {
            QWJSBridge.queue.commands.push(arguments);
            if(QWJSBridge.queue.timer == null) {
                QWJSBridge.queue.timer = setInterval(QWJSBridge.run_command, 10);
            }
        };
        QWJSBridge.run_command = function () {
            if(!QWJSBridge.queue.ready) {
                return;

            }
            QWJSBridge.queue.ready = false;
            if(!this.jsBridge) {
                this.jsBridge = document.createElement("iframe");
                this.jsBridge.setAttribute("style", "display:none;");
                this.jsBridge.setAttribute("height", "0px");
                this.jsBridge.setAttribute("width", "0px");
                this.jsBridge.setAttribute("frameborder", "0");
                document.documentElement.appendChild(this.jsBridge);
            }
            var args = QWJSBridge.queue.commands.shift();
            if(QWJSBridge.queue.commands.length == 0) {
                clearInterval(QWJSBridge.queue.timer);
                QWJSBridge.queue.timer = null;
            }
            var service;
            var callbackId = null;
            var start = 0;
            try {
                if(args[0] == null || typeof args[0] === "function") {
                    var callback = args[0];
                    service = args[1] + "." + args[2];
                    args = args[3]; //array of arguments to
                    callbackId = service + QWJSBridge.callbackId++;
                    if(callback) {
                        QWJSBridge.callbacks[callbackId] = {
                            callback: callback
                        };
                    }
                } else {
                    service = args[0];
                    start = 1;
                }
                var uri = [];
                var dict = null;

                if(args != null) {
                    for (var i = start; i < args.length; i++) {
                        var arg = args[i];
                        if(arg == undefined || arg == null)
                            continue;
                        if(typeof(arg) == 'object') {
                            dict = arg;
                        } else {
                            uri.push(encodeURIComponent(arg));
                        }
                    }
                }
                var next = callbackId != null ? ("/" + callbackId + "/") : "/";
                var url = "emp://" + QWJSBridge.sessionKey + "@" + service + next + uri.join("/");
                if(dict != null) {
                    url += "?" + encodeURIComponent(JSON.stringify(dict));
                }
                this.jsBridge.src = url;
            } catch (e) {
                alert(e);
                console.log("QWIOSJSBridgeExec Error: " + e);
            }
        };
        QWJSBridge.callback = function (callbackId, args) {
            if(QWJSBridge.callbacks[callbackId]) {
                // If result is to be sent to callback
                try {

                    QWJSBridge.callbacks[callbackId].callback(args.message);
                } catch (e) {
                    console.log("Error in success callback: " + callbackId + " = " + e);
                }
                if(!args.keepCallback) {
                    delete QWJSBridge.callbacks[callbackId];
                }
            }
        };
    }

    /***************************************************  继承QWJSBridge基类  *******************************************************/
//用户是否登入
    if(!QWJSBridge.hasResource("loginPlugin")) {
        QWJSBridge.addResource("loginPlugin");

        var loginPlugin = function () {
        }

        loginPlugin.login = function (loginCallback) {
            QWJSBridge.exec(loginCallback, "PluginLogin", "login", []);
        };
        loginPlugin.logout = function () {
            QWJSBridge.exec(logoutCallback, "PluginLogin", "logout", []);
        };
    }
//二维码扫描
    if(!QWJSBridge.hasResource("scanner")) {
        QWJSBridge.addResource("scanner");
        var scanner = function () {
        }
        scanner.startScanner = function () {
            QWJSBridge.exec(fillDate, "PluginScanner", "startScanner", []);
        };
    }
//获取定位参数
    if(!QWJSBridge.hasResource("locationFun")) {
        QWJSBridge.addResource("locationFun");

        var locationFun = function () {

        }
        locationFun.startLocation = function () {
            QWJSBridge.exec(getLocationInfo, "PluginLocation", "getCurrentLocation", []);
        };
    }
// app回调
    if(!QWJSBridge.hasResource("returnFun")) {
        QWJSBridge.addResource("returnFun");

        var returnFun = function () {

        }
        returnFun.refresh = function (fillDate) {
            QWJSBridge.exec(fillDate, "PluginCommon", "", []);
        };
    }
//{"title":"咨询药师","pageType":"1","url":"/api/index.html","jumpType":"1","params":{"token":"232342342342343","branchId":"32423424234"}}
//title:头部名称
//pageType：对应页码
//url：跳转至H5页面地址
//jumpType：1，h5到原生   2，h5 到 h5
//params：页面上需要的参数
//H5页面调用原生页面
//type类型
    /*
     1：用户咨询页面(聊天)
     2: 我也要问页面
     3：添加更多慢病订阅
     4：去添加慢病(引导页跳转至app页面)
     * */
    if(!QWJSBridge.hasResource("skipApp")) {
        QWJSBridge.addResource("skipApp");
        var skipApp = function () {

        }
        var fillDate = function () {

        }
        skipApp.startSkipApp = function (obj) {
            QWJSBridge.exec(fillDate, "PluginSkipApp", "startSkipApp", [obj]);
        };
    }
//var type={"type":"1","message":"","url":'',"params":""};
//调用原生插件
    /*
     1: 搜藏
     2：打电话
     3：分享
     4：弹出提示框
     5：
     8:关闭当前页面
     14:'调用标题'
     19:显示
     20:隐藏
     21:跳首页
     23:客服咨询
     * */
    if(!QWJSBridge.hasResource("appPlugin")) {
        QWJSBridge.addResource("appPlugin");
        var appPlugin = function () {

        }
        var fillDate = function () {

        }
        appPlugin.startAppPlugin = function (type) {
            QWJSBridge.exec(fillDate, "PluAppPlugin", "startAppPlugin", [type]);
        };
    }

//获取设备号id
    if(!QWJSBridge.hasResource("appDevice")) {
        QWJSBridge.addResource("appDevice");
        var appDevice = function () {

        }
        appDevice.startAppDevice = function () {
            QWJSBridge.exec(getDevice, "QWDevice", "getDeviceInfo", []);
        };
    }
//添加埋点,统计数据
    if(!QWJSBridge.hasResource("appPoint")) {
        QWJSBridge.addResource("appPoint");
        var appPoint = function () {

        }
        appPoint.startAppPoint = function (obj) {
            QWJSBridge.exec(getPoint, "Point", "getPointInfo", [obj]);
        };
    }
//获取token
    if(!QWJSBridge.hasResource("appToken")) {
        QWJSBridge.addResource("appToken");
        var appToken = function () {


        };
        appToken.startAppToken = function () {
            QWJSBridge.exec(getToken, "gToken", "getTokenInfo", []);
        };
        appToken.startAppToken = function (getToken) {
            QWJSBridge.exec(getToken, "gToken", "getTokenInfo", []);
        }
    }
// 积分商城--收货地址
    if(!QWJSBridge.hasResource("PluginShippingAddress")) {
        QWJSBridge.addResource("PluginShippingAddress");

        var PluginShippingAddress = function () {
        }
        // 地址列表
        PluginShippingAddress.getAddressInfo = function () {
            QWJSBridge.exec(getAddress, "ShippingAddress", "getAddressInfo", []);
        };
        // 新地址
        PluginShippingAddress.getNewAddress = function () {
            QWJSBridge.exec(getAddress, "ShippingAddress", "getNewAddress", []);
        };
    }
//问答详情--获取答案
    if(!QWJSBridge.hasResource("PShippingDiscovery")) {
        QWJSBridge.addResource("PShippingDiscovery");
        var PShippingDiscovery = function () {
        }
        PShippingDiscovery.getDiscoveryInfo = function () {
            QWJSBridge.exec(getDiscovery, "PluginShippingDiscovery", "getDiscoveryInfo", []);
        };
    }

    //获取支付参数信息
    if(!QWJSBridge.hasResource("PluginPay")) {
        QWJSBridge.addResource("PluginPay");
        var PluginPay = function () {
        }
        var fillDate = function () {

        }
        PluginPay.get = function (params) {
            QWJSBridge.exec(params, "PluginPay", "getParams", []);
        };
        PluginPay.sendurl = function (params) {
            QWJSBridge.exec(fillDate, "PluginPay", "sendUrl", [params]);
        };
        PluginPay.weifutongPay = function (params) {
            console.log('weifutongPay', params);
            QWJSBridge.exec(fillDate, "PluginPay", "weifutongPay", [params]);
        };

    }

    window.QWJSBridge = QWJSBridge;
    window.TDbridge = {
        loginPlugin: loginPlugin,
        scanner: scanner,
        locationFun: locationFun,
        skipApp: skipApp,
        appToken: appToken,
        returnFun: returnFun,
        appPlugin: appPlugin,
        appDevice: appDevice,
        PluginPay,
    };
})();
export default TDbridge ;
